package com.itheima.servlet01;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet("/studentServlet01")
public class StudentServlet01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取表单数据
        String username = req.getParameter("username");
        String age = req.getParameter("age");
        String scare = req.getParameter("scare");

        try {
            //保存到相对路径的绝对路径下
            //获取ServletContext对象
            ServletContext servletContext = super.getServletContext();
            //根据配置的键读取值
            String configName = servletContext.getInitParameter("users");
            //获取路径
            String path = servletContext.getRealPath("/" + configName);
            //根据路径新建缓冲字符输出流
            BufferedWriter bw = new BufferedWriter(new FileWriter(path, true));
            bw.write(username+","+age+","+scare);
            //换行
            bw.newLine();
            bw.close();
            //写入成功的反馈
            PrintWriter pw = resp.getWriter();
            pw.print("succeed");

        } catch (IOException e) {
            //写入失败的反馈
            PrintWriter pw = resp.getWriter();
            pw.print("defeated");
            e.printStackTrace();
        }
    }

    @Override
    protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doHead(req, resp);
    }
}
